package fr.cdj.thebox.server;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;

import fr.cdj.thebox.server.generated.GeneratedConf;
import fr.cdj.thebox.server.generated.ObjectFactory;

public final class XmlLoader {

	private static final String CONF_XML_FILE_NAME = "/xml/conf.xml";
	private static final String CONF_SCHEMA_FILE_NAME = "/xml/conf.xsd";

	private XmlLoader() {
	}

	public static GeneratedConf generateConfFromXmlFile() {
		InputStream flux = XmlLoader.class.getClassLoader().getResourceAsStream(CONF_XML_FILE_NAME);
		try {
			
			final JAXBContext context = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
			final Unmarshaller unmarsh = context.createUnmarshaller();
			
			final SchemaFactory schemaFactory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
			final Schema schema = schemaFactory.newSchema(XmlLoader.class.getClassLoader().getResource(CONF_SCHEMA_FILE_NAME));
			unmarsh.setSchema(schema);

			return (GeneratedConf) unmarsh.unmarshal(flux);
		} catch (JAXBException | SAXException e) {
			e.printStackTrace();
		} finally {
			try {
				flux.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
